import React, { useRef, useState, useEffect } from 'react';
import {
  View,
  Image,
  ImageBackground,
  StyleSheet,
  StatusBar,
  TouchableOpacity,
  Text,
  Keyboard,
  Dimensions,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import {
  Button,
  List,
  Picker,
  Toast,
  InputItem,
  ActivityIndicator,
  Modal,
  Result,
  Flex,
} from '@ant-design/react-native';
import { IconX } from '@/rcomponents/iconx';
import LoginStore from '@/stores/loginStore';
import { getValue } from '@/services/asyncStorage';
import VerifyCodeInput from './codeVerifyInput';
import { isIos } from '../../constants';

const styles = StyleSheet.create({
  imageBg: {
    flex: 1,
  },
  loginActionSection: {
    justifyContent: 'center',
    position: 'absolute',
    bottom: Dimensions.get('window').height / 7,
    width: '100%',
  },
  hpadding15: { paddingHorizontal: 15, backgroundColor: 'transparent' },
  passwordTouchbar: {
    position: 'absolute',
    justifyContent: 'flex-end',
    top: 0,
    bottom: 0,
    right: 0,
  },
  sentMsgText: {
    fontSize: 18,
    color: 'orange',
    paddingHorizontal: 20,
  },
  touchablePadding: {
    padding: 10,
  },
  loginBtn: {
    marginTop: 10,
    marginHorizontal: 10,
  },
});

function LoginScreen() {
  const loginStore = LoginStore.useStore();
  const [direction, setDirection] = useState(true); // 是否竖屏
  const [mrsForm, setMrsForm] = useState({
    sendType: '0',
    sendto: '',
    code: '',
  });

  const inputPassword = useRef();

  const handleLayoutChange = (ev) => {
    const { x, y, width, height } = ev.nativeEvent.layout;
    setDirection(y + height > x + width);
  };
  useEffect(() => {
    if (loginStore.mrsauthState.action === 'relogin') {
      loginStore.checkInnerLoongair(null, true);
    }
  }, [loginStore, loginStore.mrsauthState.action]);
  useEffect(() => {
    async function refillSendType() {
      const gjsendVerify = await getValue('gjverify');
      if (gjsendVerify && gjsendVerify.send_type) {
        setMrsForm({
          ...mrsForm,
          sendType: gjsendVerify.send_type,
          sendto: gjsendVerify.sendto,
        });
      }
    }
    refillSendType();
    StatusBar.setHidden(true);
    return () => {
      StatusBar.setHidden(false);
    };
  }, []);

  const onSubmit = () => {
    inputPassword.current.focus();
  };

  const [pwdVisible, setPwdVisible] = useState(false);
  const { username, password } = loginStore.credentials;
  const { mrsauthState } = loginStore;

  const handleLogin = async () => {
    Keyboard.dismiss();

    if (!username) {
      Toast.fail('登录用户名必填', 1);
      return;
    }
    if (!password) {
      Toast.fail('用户密码必填', 1);
      return;
    }

    const loginErrMsg = await loginStore.loginUser();
    if (loginErrMsg) {
      Toast.fail(loginErrMsg);
    }
  };

  const handleSendVerifyCode = async () => {
    Keyboard.dismiss();
    if (!mrsForm.sendto) {
      Toast.fail('发送账号必填', 1);
      return;
    }
    const loginErrMsg = await loginStore.sendVerifyCode(mrsForm);
    if (loginErrMsg) {
      Toast.fail(loginErrMsg);
    }
  };
  const handleResendVerifyCode = async () => {
    const loginErrMsg = await loginStore.resendVerifyCode(mrsForm);
    if (loginErrMsg) {
      Toast.fail(loginErrMsg);
    }
  };
  const handleVerifyCode = async (mrsFormParam) => {
    const mrsFormArg = mrsFormParam || mrsForm;
    Keyboard.dismiss();
    if (!mrsFormArg.code) {
      Toast.fail('验证码未填写', 1);
      return;
    }
    const verifyErr = await loginStore.verifyAuthCode(mrsFormArg);
    if (verifyErr) {
      Modal.alert(verifyErr.title, verifyErr.msg);
    }
    if (mrsFormParam) {
      setMrsForm(mrsFormParam);
    }
  };
  let loginView = <ActivityIndicator />;
  let actionBtn = null;
  if (mrsauthState.action === 'login') {
    actionBtn = (
      <>
        <Button
          type="primary"
          loading={loginStore.loginUser.loading}
          style={styles.loginBtn}
          onPress={handleLogin}
        >
          登录
        </Button>
      </>
    );
    loginView = (
      <List style={styles.hpadding15}>
        <InputItem
          placeholder="用户名/OA账号"
          style={styles.inputText}
          autoCapitalize="none"
          returnKeyType={'next'}
          onSubmitEditing={onSubmit}
          onChangeText={(text) =>
            loginStore.setCredentials({
              username: text,
            })
          }
          labelNumber={1.5}
          value={username}
        >
          <Image source={require('@/assets/images/user.png')} />
        </InputItem>
        <View>
          <InputItem
            ref={inputPassword}
            returnKeyType={'go'}
            onSubmitEditing={handleLogin}
            onChangeText={(text) =>
              loginStore.setCredentials({
                password: text,
              })
            }
            placeholder="密码"
            value={password}
            style={styles.inputText}
            labelNumber={1.5}
            type={pwdVisible ? undefined : 'password'}
          >
            <Image source={require('@/assets/images/password.png')} />
          </InputItem>
          <View style={styles.passwordTouchbar}>
            <TouchableOpacity onPress={() => setPwdVisible(!pwdVisible)}>
              <View style={styles.touchablePadding}>
                <IconX name={pwdVisible ? 'md-eye' : 'md-eye-off'} />
              </View>
            </TouchableOpacity>
          </View>
        </View>
      </List>
    );
  } else if (mrsauthState.action === 'send') {
    actionBtn = (
      <Button
        type="primary"
        loading={loginStore.sendVerifyCode.loading}
        style={styles.loginBtn}
        onPress={handleSendVerifyCode}
      >
        获取验证码
      </Button>
    );
    let placeholder = '手机号';
    if (mrsForm.sendType === '0') {
      placeholder = 'OA账号';
    } else if (mrsForm.sendType === '2') {
      placeholder = '邮箱@';
    }
    loginView = (
      <List style={styles.hpadding15}>
        <Picker
          data={[
            { value: '0', label: '企业OA' },
            { value: '1', label: '短信' },
            { value: '2', label: '邮箱' },
          ]}
          cols={1}
          value={mrsForm.sendType}
          onChange={(value) => {
            setMrsForm({ ...mrsForm, sendType: value[0] });
          }}
        >
          <List.Item arrow="horizontal">验证方式</List.Item>
        </Picker>
        <InputItem
          placeholder={placeholder}
          style={styles.inputText}
          autoCapitalize="none"
          returnKeyType={'next'}
          onSubmitEditing={handleSendVerifyCode}
          onChangeText={(text) => setMrsForm({ ...mrsForm, sendto: text })}
          labelNumber={1.5}
          value={mrsForm.sendto}
        />
      </List>
    );
  } else if (mrsauthState.action === 'verify') {
    let sentMsg = '验证码已发送至: ';
    if (mrsForm.sendType === '0') {
      sentMsg = `${sentMsg}企业微信`;
    } else if (mrsForm.sendType === '1') {
      sentMsg = `${sentMsg}${mrsForm.sendto.slice(
        0,
        -8,
      )}****${mrsForm.sendto.slice(-4)}`;
    } else if (mrsForm.sendType === '2') {
      sentMsg = `${sentMsg}${mrsForm.sendto}`;
    }
    actionBtn = (
      <>
        <Button
          type="primary"
          loading={loginStore.verifyAuthCode.loading}
          disabled={loginStore.resendVerifyCode.loading}
          style={styles.loginBtn}
          onPress={handleVerifyCode}
        >
          验证
        </Button>
        <Flex>
          <Flex.Item>
            <Button
              type="ghost"
              loading={loginStore.resendVerifyCode.loading}
              disabled={loginStore.verifyAuthCode.loading}
              style={styles.loginBtn}
              onPress={handleResendVerifyCode}
            >
              重新获取验证码
            </Button>
          </Flex.Item>
          <Flex.Item>
            <Button
              type="ghost"
              style={styles.loginBtn}
              onPress={async () => {
                await loginStore.logoutUser();
              }}
            >
              返回登录页面
            </Button>
          </Flex.Item>
        </Flex>
      </>
    );
    loginView = (
      <>
        <Text style={styles.sentMsgText}>{sentMsg}</Text>
        <VerifyCodeInput
          verifyCodeLength={4}
          onChange={(val) => {
            handleVerifyCode({ ...mrsForm, code: val });
          }}
        />
      </>
    );
  } else if (mrsauthState.action === 'retry') {
    loginView = (
      <Result
        title="网络连接异常"
        message={mrsauthState.retryErrReason}
        buttonText="重试"
        onButtonClick={() => loginStore.checkInnerLoongair(null, true)}
      />
    );
  }

  return (
    <ImageBackground
      source={
        Platform.isPad
          ? direction
            ? require('@/assets/images/loginbgIpad.png') //横屏
            : require('@/assets/images/ipadVertical.png') //竖屏
          : require('@/assets/images/loginbg.png')
      }
      style={styles.imageBg}
    >
      <KeyboardAvoidingView
        style={styles.loginActionSection}
        behavior={isIos ? 'padding' : 'position'}
      >
        <View onLayout={handleLayoutChange}>
          {loginView}
          {actionBtn}
        </View>
      </KeyboardAvoidingView>
    </ImageBackground>
  );
}

LoginScreen.routeName = 'LoginScreen';

export default LoginScreen;
